import { Context } from "koa";

export function formatSql(sql: string, values: any[]): string {
  let formatted = sql;
  values.forEach((value) => {
    // 对字符串和日期类型加引号
    if (typeof value === "string" || value instanceof Date) {
      formatted = formatted.replace("?", `'${value}'`);
    } else if (value === null) {
      formatted = formatted.replace("?", "NULL");
    } else {
      formatted = formatted.replace("?", String(value));
    }
  });
  return formatted;
}
export function getClientIp(ctx: Context) {
  const xForwardedFor = ctx.headers["x-forwarded-for"];
  let forwardedIp: string | undefined;

  if (typeof xForwardedFor === "string") {
    forwardedIp = xForwardedFor.split(",")[0]?.trim();
  } else if (Array.isArray(xForwardedFor) && xForwardedFor.length > 0) {
    forwardedIp = xForwardedFor[0].split(",")[0]?.trim();
  }

  let clientIp =
    ctx.headers["x-real-ip"]?.[0] ||
    forwardedIp ||
    ctx.headers["proxy-client-ip"]?.[0] ||
    ctx.headers["wl-proxy-client-ip"]?.[0] ||
    ctx.ip;

  if (!clientIp) return "unknown";

  const ipv4MappedRegex = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/;
  const ipv4MappedMatch = clientIp.match(ipv4MappedRegex);
  if (ipv4MappedMatch) {
    return ipv4MappedMatch[1];
  }

  if (clientIp === "::1") {
    return "127.0.0.1";
  }

  return clientIp;
}
